# -*- coding: utf-8 -*-

import smtplib
import os
try:
    import ConfigParser
except:
    import configparser as ConfigParser

from email.mime.text import MIMEText
from core import settings

class Mail:

    cf = None
    server = None
    instance = None

    def __init__(self):
        self.cf = settings.Email
        
        self.connect()

    def connect(self):
        if self.server is not None:
            return self.server

        self.server = smtplib.SMTP_SSL(self.getConfig('host'), int(self.getConfig('port')))
        #self.server.set_debuglevel(1)
        self.server.login(self.getConfig('user'), self.getConfig('pass'))
        return self.server

    def getConfig(self, key):
        return self.cf.get(key)

    def send(self,  content=' ', subject='Python', emails=[]):
        if len(emails) == 0:
            emails = self.getConfig('toemails').split(',')
        msg = MIMEText(content)
        msg['Subject'] = subject
        msg['To'] = ','.join(emails)
        msg['From'] = self.getConfig('user')

        return self.server.sendmail(self.getConfig('user'), emails, msg.as_string())

    def close(self):
        return self.server.quit()

    @staticmethod
    def sendMail(msg, subject='Python', emails=[]):
        m = Mail()
        m.send(msg, subject, emails)
        m.close()

#############################
#mail.sendMail('sfsfs', 'xxxx')
#############################
if __name__ == '__main__':
    Mail.sendMail('content', 'subject')
